﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EntityComponentSystem.Framework
{
    public static class Helpers
    {
        public static void EscapeWithStringBuilder(StringBuilder sb, string source)
        {
            var data = source;
            int lastwrite = 0;
            for (int i = 0; i < data.Length; i++)
            {
                var ch = data[i];
                if (ch == '\n' || ch == '\"' || ch == '\\' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b')
                {
                    lastwrite = escape(sb, data, lastwrite, i);
                    switch (ch)
                    {
                        case '\n': sb.Append("\\n"); break;
                        case '\r': sb.Append("\\r"); break;
                        case '\b': sb.Append("\\b"); break;
                        case '\t': sb.Append("\\t"); break;
                        default:
                            sb.Append('\\');
                            sb.Append(ch);
                            break;
                    }
                }
            }
            lastwrite = escape(sb, data, lastwrite, data.Length);
        }

        public static string Escape(string source)
        {
            var sb = new StringBuilder();
            EscapeWithStringBuilder(sb, source);
            return sb.ToString();
        }

        private static int escape(StringBuilder sb, string data, int lastwrite, int pos)
        {
            if (pos - lastwrite > 0)
                sb.Append(data, lastwrite, pos - lastwrite);

            return pos + 1;
        }

    }
}
